package com.tchepannou.limbe.interceptor;

import com.tchepannou.limbe.Controller;
import com.tchepannou.limbe.Interceptor;
import com.tchepannou.limbe.annotation.WebParam;
import com.tchepannou.limbe.annotation.WebParams;
import com.tchepannou.limbe.web.ActionController;
import com.tchepannou.util.StringUtil;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * User: herve
 * Date: 14-01-12 2:34 PM
 */
public class WebParamInterceptor implements Interceptor
{
    @Override
    public int before(Controller controller)
    {
        return Interceptor.CONTINUE;
    }

    @Override
    public void after(Controller controller)
    {
    }

    @Override
    public int before(Method method, Controller controller)
    {
        if (controller instanceof ActionController)
        {
            return before(method, (ActionController)controller);
        }
        return Interceptor.CONTINUE;
    }

    private int before(Method method, ActionController controller)
    {
        WebParams anno = method.getAnnotation(WebParams.class);
        if (anno != null)
        {
            for (WebParam param : anno.params())
            {
                String name = param.name();
                String value = controller.getRequestParameter(name);
                if (param.required() && StringUtil.isEmpty(value))
                {
                    return error(name, controller);
                }
            }
        }
        return Interceptor.CONTINUE;
    }

    private int error(String name, ActionController controller)
    {
        try
        {
            String message = "Missing parameter: " + name;
            controller.sendError(400, message);
            controller.getResponse().sendError(400, message);
            return Interceptor.STOP;
        }
        catch (IOException e)
        {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void after(Method method, Controller controller, Throwable throwable)
    {
    }
}
